package br.com.opet.DAO;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.opet.vo.Cliente;
import br.com.opet.vo.Usuario;

public class ClienteDAO {
	public static boolean insert(Cliente cliente)
	{
		try{
			EntityManager manager = EntityManagerFactory.getInstance();
			manager.getTransaction().begin();
			manager.persist(cliente);
			manager.getTransaction().commit();
			return true;			
		}
		catch(Exception e){
			return false;
		}
	}
	
	public static Cliente SearchById(int idCliente)
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Cliente where id = :idP");
			q.setParameter("idP", idCliente);
			List<Cliente> clientes = q.getResultList();
			if(!clientes.isEmpty()){
				return clientes.get(0);								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	public static Cliente SearchByEmail(Cliente cliente)
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Cliente where email = :emailP");
			q.setParameter("emailP", cliente.getEmail());
			List<Cliente> clientes = q.getResultList();
			if(!clientes.isEmpty()){
				return clientes.get(0);								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	public static List<Cliente> listAll()
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Cliente order by nome");
			List<Cliente> clientes = q.getResultList();
			if(!clientes.isEmpty()){
				return clientes;								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	public static Cliente checkUser(Cliente cliente)
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Cliente where email = :emailP ");
			q.setParameter("emailP", cliente.getEmail());
			List<Cliente> clientes = q.getResultList();
			if(!clientes.isEmpty()){
				if(clientes.get(0).getSenha().equals(cliente.getSenha()))
				{
					return clientes.get(0);
				}
				else
				{
					return null;
				}				
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	public static boolean remove(int idCliente)
	{
		try{
			Cliente us = SearchById(idCliente);		
			EntityManager manager = EntityManagerFactory.getInstance();
			manager.getTransaction().begin();
			manager.remove(us);
			manager.getTransaction().commit();
			return true;			
		}
		catch(Exception e){
			return false;
		}
	}
}
